#include "serialcomm.h"

SerialComm::SerialComm(QObject *parent)
    : Fsu{parent}
{
    serialPort = new QSerialPort(this);
    connect(serialPort, &QSerialPort::readyRead, this, &SerialComm::readyRead);
}

void SerialComm::open(const QString &parameter)
{
    //PortName:BaudRate:DataBits:Parity:StopBits
    QStringList list = parameter.split(':');
    serialPort->setPortName(list[0]);
    if (serialPort->open(QIODevice::ReadWrite))
    {
        serialPort->setBaudRate(list[1].toInt());
        serialPort->setDataBits(QSerialPort::DataBits(list[2].toInt()));
        serialPort->setParity(QSerialPort::Parity(list[3].toInt()));
        serialPort->setStopBits(QSerialPort::StopBits(list[4].toInt()));
        serialPort->setFlowControl(QSerialPort::NoFlowControl);

        emit opened();
    }
    else
    {
        emit closed();
    }
}

void SerialComm::write(const QByteArray &data)
{
    serialPort->write(data);
}

void SerialComm::close()
{
    serialPort->close();
    emit closed();
}

void SerialComm::readyRead()
{
    QByteArray data = serialPort->readAll();
    emit received(data);
}
